package org.example.cdpcrpbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.cdpcrpbackend.controller.dto.CrpItem1;
import org.example.cdpcrpbackend.controller.dto.Result;
import org.example.cdpcrpbackend.domain.CrpItem;
import org.example.cdpcrpbackend.service.CrpItemService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/crp-item")
@RequiredArgsConstructor
public class CrpItemController {
    private final CrpItemService service;

    /**
     * 申请-培养项目列表
     * mid 为空时，返回全部
     *
     * @param mid 模块id
     */
    @GetMapping
    public Result list(@RequestParam(value = "mid", required = false) String mid,
                       @RequestParam(value = "search", required = false) String search) {
        List<CrpItem> list;
        if (mid != null && !mid.equals("0")) {
            LambdaQueryWrapper<CrpItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrpItem::getCrpModuleId, mid);
            list = service.list(wrapper);
        } else {
            list = service.list();
        }

        if (search == null || search.isEmpty()) {
            return Result.success(list);
        }

        // 过滤搜索条件
        List<CrpItem> collect = list.stream()
                .filter(item -> {
                    if (item.getName().contains(search) || item.getContent().contains(search)) {
                        return true;
                    } else {
                        return false;
                    }
                })
                .collect(Collectors.toList());
//        System.out.println(collect);

        return Result.success(collect);
    }

    /**
     * 申请-培养项目详情
     *
     * @param id 培养项目id
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id) {
        CrpItem1 item = service.getItemAndModById(id);
        return Result.success(item);
    }
}
